#include "doctor_client.h"
#include <QVBoxLayout>
#include <QTabWidget>
#include <QListWidget>
#include <QLabel>
#include <QSqlError>
#include <QSqlQuery>
#include <QPushButton>
#include <QDateTime>
#include <QMessageBox>
#include <QDebug>

// 构造函数，传入 doctorId
DoctorClient::DoctorClient(int doctorId, QWidget *parent)
    : QWidget(parent), doctorId(doctorId) // 初始化 doctorId
{
    setWindowTitle("Doctor Client");
    resize(600, 400);
    setupUI();  // 使用 setupUI 函数初始化界面
}

// 返回当前医生的 ID
int DoctorClient::getCurrentDoctorId() const
{
    return doctorId;
}

void DoctorClient::onRefreshAppointments()
{
    loadAppointments();
}

void DoctorClient::setupUI()
{
    QTabWidget *tabWidget = new QTabWidget(this);

    // --- 患者列表界面 ---
    QWidget *patientListTab = new QWidget();
    QVBoxLayout *patientListLayout = new QVBoxLayout(patientListTab);
    QListWidget *patientListWidget = new QListWidget(patientListTab);
    QPushButton *viewRecordButton = new QPushButton("查看病历", patientListTab);

    // 从数据库获取患者列表
    QSqlQuery query("SELECT DISTINCT patients.name FROM medical_history "
                    "JOIN patients ON medical_history.patient_id = patients.patient_id");

    if (!query.exec()) {
        QMessageBox::warning(this, "数据库错误", "查询患者列表失败：" + query.lastError().text());
        return;
    }

    while (query.next()) {
        patientListWidget->addItem(query.value(0).toString());
    }

    patientListLayout->addWidget(patientListWidget);
    patientListLayout->addWidget(viewRecordButton); // 将按钮添加到患者列表布局中
    patientListTab->setLayout(patientListLayout); // 设置布局
    tabWidget->addTab(patientListTab, "患者列表");

    // --- 查看病历页面 ---
    QWidget *viewRecordTab = new QWidget();
    QVBoxLayout *viewRecordLayout = new QVBoxLayout(viewRecordTab);
    QLabel *patientInfoLabel = new QLabel(viewRecordTab);
    QLabel *recordLabel = new QLabel(viewRecordTab);
    patientInfoLabel->setWordWrap(true); // 使标签支持换行显示
    recordLabel->setWordWrap(true); // 使标签支持换行显示

    viewRecordLayout->addWidget(patientInfoLabel);
    viewRecordLayout->addWidget(recordLabel);
    viewRecordTab->setLayout(viewRecordLayout); // 设置布局
    tabWidget->addTab(viewRecordTab, "查看病历");

    // 点击按钮后显示选中患者的所有病历并切换到“查看病历”页面
    connect(viewRecordButton, &QPushButton::clicked, [ = ]() {
        QListWidgetItem *selectedItem = patientListWidget->currentItem();
        if (!selectedItem) {
            QMessageBox::warning(this, "提示", "请先选择一名患者。");
            return;
        }

        QString patientName = selectedItem->text();
        QSqlQuery query;

        // 获取当前医生ID
        int currentDoctorId = getCurrentDoctorId();

        // 查询患者的基本信息和病历信息，同时检查是否是该医生的患者
        query.prepare("SELECT patients.name, patients.gender, patients.phone, d.name AS doctor_name, "
                      "mh.diagnosis, mh.treatment, mh.visit_date "
                      "FROM medical_history mh "
                      "JOIN patients ON mh.patient_id = patients.patient_id "
                      "JOIN doctors d ON mh.doctor_id = d.doctor_id "
                      "WHERE patients.name = ? AND mh.doctor_id = ?");
        query.addBindValue(patientName);
        query.addBindValue(currentDoctorId);

        QString recordText;
        QString patientInfoText;

        if (!query.exec()) {
            QMessageBox::warning(this, "错误", "无法获取病历：" + query.lastError().text());
            return;
        }

        // 检查是否有病历记录
        bool hasRecords = false;
        while (query.next()) {
            hasRecords = true;

            // 获取患者基本信息
            QString name = query.value(0).toString();
            QString gender = query.value(1).toString();
            QString phone = query.value(2).toString();
            QString doctorName = query.value(3).toString();

            // 获取病历记录
            QString diagnosis = query.value(4).toString();
            QString treatment = query.value(5).toString();
            QString visitDate = query.value(6).toString();

            // 组织病历文本
            recordText.append(QString("就诊日期: %1\n诊断: %2\n治疗: %3\n\n")
                              .arg(visitDate, diagnosis, treatment));

            // 组织患者基本信息文本
            patientInfoText = QString("姓名: %1\n性别: %2\n电话: %3\n主治医生: %4\n")
                              .arg(name, gender, phone, doctorName);
        }

        if (!hasRecords) {
            patientInfoLabel->setText("无权限查看该患者的病历记录。");
            recordLabel->clear();
        } else {
            patientInfoLabel->setText(patientInfoText); // 显示患者基本信息
            recordLabel->setText(recordText); // 显示所有病历记录
        }

        // 切换到“查看病历”页面
        tabWidget->setCurrentIndex(1);
    });

    // --- 预约管理页面 ---
    QWidget *appointmentTab = new QWidget();
    QVBoxLayout *appointmentLayout = new QVBoxLayout(appointmentTab);
    appointmentListWidget = new QListWidget(appointmentTab);
    confirmButton = new QPushButton("确认预约", appointmentTab);
    rejectButton = new QPushButton("拒绝预约", appointmentTab);

    appointmentLayout->addWidget(new QLabel("待处理的预约请求：", appointmentTab));
    appointmentLayout->addWidget(appointmentListWidget);
    appointmentLayout->addWidget(confirmButton);
    appointmentLayout->addWidget(rejectButton);
    appointmentTab->setLayout(appointmentLayout);
    tabWidget->addTab(appointmentTab, "预约管理");

    connect(confirmButton, &QPushButton::clicked, this, &DoctorClient::onConfirmAppointment);
    connect(rejectButton, &QPushButton::clicked, this, &DoctorClient::onRejectAppointment);

    loadAppointments();  // 加载预约请求列表

    // 设置主布局
    QVBoxLayout *mainLayout = new QVBoxLayout(this);
    mainLayout->addWidget(tabWidget);
    setLayout(mainLayout);
}

void DoctorClient::loadAppointments()
{
    appointmentListWidget->clear();

    QSqlQuery query;
    query.prepare("SELECT a.appointment_id, p.name, a.appointment_date, a.status "
                  "FROM appointments a "
                  "JOIN patients p ON a.patient_id = p.patient_id "
                  "WHERE a.doctor_id = ? AND a.status = 'pending'");
    query.addBindValue(doctorId);

    if (query.exec()) {
        while (query.next()) {
            int appointmentId = query.value(0).toInt();
            QString patientName = query.value(1).toString();
            QString appointmentDate = query.value(2).toDateTime().toString("yyyy-MM-dd HH:mm");

            QString itemText = QString("预约ID: %1\n患者: %2\n时间: %3\n")
                               .arg(appointmentId).arg(patientName).arg(appointmentDate);

            QListWidgetItem *item = new QListWidgetItem(itemText, appointmentListWidget);
            item->setData(Qt::UserRole, appointmentId); // 存储预约ID
        }
    } else {
        QMessageBox::warning(this, "加载失败", "无法加载预约请求: " + query.lastError().text());
    }
}

void DoctorClient::onConfirmAppointment()
{
    QListWidgetItem *selectedItem = appointmentListWidget->currentItem();
    if (!selectedItem) {
        QMessageBox::warning(this, "未选择", "请选择一个预约请求");
        return;
    }

    int appointmentId = selectedItem->data(Qt::UserRole).toInt();

    QSqlQuery query;
    query.prepare("UPDATE appointments SET status = 'confirmed' WHERE appointment_id = ?");
    query.addBindValue(appointmentId);

    if (query.exec()) {
        QMessageBox::information(this, "成功", "预约已确认！");
        loadAppointments(); // 刷新列表
    } else {
        QMessageBox::warning(this, "失败", "无法确认预约: " + query.lastError().text());
    }
}

void DoctorClient::onRejectAppointment()
{
    QListWidgetItem *selectedItem = appointmentListWidget->currentItem();
    if (!selectedItem) {
        QMessageBox::warning(this, "未选择", "请选择一个预约请求");
        return;
    }

    int appointmentId = selectedItem->data(Qt::UserRole).toInt();

    QSqlQuery query;
    query.prepare("UPDATE appointments SET status = 'rejected' WHERE appointment_id = ?");
    query.addBindValue(appointmentId);

    if (query.exec()) {
        QMessageBox::information(this, "成功", "预约已拒绝！");
        loadAppointments(); // 刷新列表
    } else {
        QMessageBox::warning(this, "失败", "无法拒绝预约: " + query.lastError().text());
    }
}
